from app.Controllers.BaseController import BaseController
from flask import request
from app.Models.Users import Users
from app.Vendor.UsersAuthJWT import UsersAuthJWT
from app.Vendor.Decorator import validator
import time
from flask import Blueprint
from app import app
user = Blueprint('user', __name__)


@user.route('/register', methods=['POST'])
@validator(name="account", rules={'required': True, 'type': 'string', 'minlength': 10, 'maxlength': 20})
@validator(name="password", rules={'required': True, 'type': 'string'})
def register(params):
    """注册
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    account    |    false    |    string   |    account    |
    |    password    |    false    |    string   |    password    |

    #### return
    - ##### json
    > {"msg": "success", "code": 200}
    @@@
    """
    filters = {
        Users.account == params['account']
    }
    userData = Users().getOne(filters)
    if(userData == None):
        user = Users(
            account=params['account'],
            password=Users.set_password(params['password']),
            create_at = int(time.time()),
            status=1)
        result = user.add(user)
        if result == True:
            return BaseController().successData(data='注册成功')
        return BaseController().error('注册失败')
    return BaseController().error('账号已注册')



@user.route('/login', methods=['POST'])
@validator(name="account", rules={'required': True, 'type': 'string', })
@validator(name="password", rules={'required': True, 'type': 'string', })
def login(params):
    """登入
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    account    |    false    |    string   |    account    |
    |    password    |    false    |    string   |    password    |

    #### return
    - ##### json
    > {"msg": "success", "code": 200}
    @@@
    """
    result = UsersAuthJWT.authenticate(params['account'], params['password'])
    return result



@user.route('/info', methods=['GET'])
def get():
    '''获取用户信息 
    @@@
    #### return
    - ##### json
    > {"msg": "success", "code": 200,"data":{id:1}}
    @@@
    '''
    result = UsersAuthJWT().identify(request)
    if isinstance(result, str):
        return BaseController().notAuth(result)
    if (result['data']):
        user = Users.get(result['data']['id'])
        returnUser = {
            'id': user.id,
        }
        return BaseController().successData(returnUser)
    return BaseController().error('未找到用户')


#token 拦截校验
@app.before_request
def before_action():
    uri = request.path
    if not (uri.startswith('/user') or uri.startswith('/doc')):
        result = UsersAuthJWT().identify(request)
        if isinstance(result, str):
            return BaseController().notAuth(result)

